package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.QuestionCollection;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.mapper.QuestionCollectionMapper;
import cn.wolfcode.trip.base.service.IQuestionCollectionService;
import cn.wolfcode.trip.base.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class QuestionCollectionServiceImpl implements IQuestionCollectionService {
    @Autowired
    private QuestionCollectionMapper questionCollectionMapper;

    @Override
    public void saveOrUpdate(QuestionCollection questionCollection) {
        if (questionCollection.getId() != null) {
            questionCollectionMapper.updateByPrimaryKey(questionCollection);
        } else {
            User currentUser = UserContext.getCurrentUser();
            if (currentUser != null) {
                //设置收藏者
                questionCollection.setCollectUser(currentUser);
                //收藏保存操作
                questionCollectionMapper.insert(questionCollection);
            }
        }
    }

    @Override
    public QuestionCollection getById(Long id) {
        return questionCollectionMapper.selectByPrimaryKey(id);
    }

    @Override
    public QuestionCollection queryById(Long questionId) {
        Long userId = UserContext.getCurrentUser().getId();
        QuestionCollection questionCollection = questionCollectionMapper.selectById(questionId, userId);

        if (questionCollection == null) {
            throw new RuntimeException("这货没有收藏这个问题啊!");
        }
        return questionCollection;
    }

    @Override
    public void deleteQuestionCollectionById(Long questionId) {
        //获取当前用户的id
        Long userId = UserContext.getCurrentUser().getId();
        System.out.println(userId);
        //取消收藏当前用户对应的问题
        questionCollectionMapper.deleteQuestionCollectionById(questionId, userId);
    }

}
